/**
 * 用户表
 */

const mongoose = require('mongoose')
const Schema = mongoose.Schema
const md5 = require('md5')
const crypto = require('crypto')
const config = require('../config')

const UserSchema = new Schema({
	nickname: {
		type: String,
		default: '游客'
	},
	username: {
		type: String,
		unique: true
	},
	password: {
		type: String,
		require: true
	},
	slogan: {
		type: String,
		default: ''
	},
	email: {
		type: String,
		require: true
	},
	avatar: {
		type: String
	},
	role: {
		type: String,
		default: 'user'
	},
	create_time: {
		type: Date,
		default: Date.now()
	},
	update_time: {
		type: Date,
		default: Date.now()
	}
})

UserSchema.path('password').set(v => crypto.createHash('md5').update(v).digest('base64'))

UserSchema.pre('save', function(next) {
	if (this.isNew) {
		this.create_time = this.update_time = Date.now()
	} else {
		this.update_time = Date.now()
	}
	next()
})

UserSchema.methods = {

}

UserSchema.statics = {
	async checkPassword(username, password) {
		const user = await this.findOne({
			username,
			password: crypto.createHash('md5').update(password).digest('base64')
		})
		return user
	}
}

mongoose.model('User', UserSchema)